/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlcommand;

import com.sun.org.apache.bcel.internal.generic.RETURN;
import data.Cell;
import data.ManagerDatabase;
import data.Row;
import java.util.ArrayList;

/**
 *
 * @author Quang
 */
public class Update extends Command{
    private String tableName;
    private ArrayList<String> colsName;
    private ArrayList<String> values;
    private String condition;
    private StringBuilder selectSql;
    private String[] strOperator = { "+","-","*","/"};
    //private ArrayList<SingleCondition> conditionSET;
    //private ArrayList<SingleCondition> conditionWhere;
    public Update(String strSQL, ManagerDatabase md){
       super(strSQL,md);
        tableName = null;
        values = new ArrayList<>();
        colsName = new ArrayList<>();
        selectSql = new StringBuilder();
        //conditionSET = new ArrayList<SingleCondition>();
       // conditionWhere = new ArrayList<SingleCondition>();
        
    }
    /**
     * phan tich cau lenh update thanh cua lenh select
     * UPDATE GIAOVIEN SET TUOI = 15, LUONG = LUONG * 1.5 WHERE MAGV ='GV001'
     * => SELECT LUONG, TUOI FROM GIAOVIEN WHERE MAGV='GV001'
     * sau do lay cac cot duoc lua chon tu cau lenh select CAP NHAT du lieu cho chung
     * @param err
     * @return 
     */
    
    public Command getCommand(MyError err){
        
        
        StringBuffer strBuff = new StringBuffer(this.sql);
        int posUpdate = strBuff.indexOf("UPDATE");
        int posSet = strBuff.indexOf("SET");
        if(posUpdate==-1 || posSet ==-1){
            err.setError("Error!! khong co tu khoa update hoac set");
            return null;
        }
        tableName  = strBuff.substring(posUpdate + 7, posSet-1);
        if(getTableName().indexOf(" ")!= -1){
           err.setError("Error! Ten bang khong duoc chua dau khoang trang");
           return null;
        }
        
        // set cac thuoc tinh
        int posWhere = strBuff.indexOf("WHERE");
        String tempSet;
        if(posWhere == -1)
            tempSet = strBuff.substring(posSet+4);
        else
            tempSet = strBuff.substring(posSet+4, posWhere);
        StringBuilder stringSet = new StringBuilder(tempSet);
        do {
            int posComma = stringSet.indexOf(",");
            if (posComma == -1) {
                if (getAndSaveColsNameAndValuesName(stringSet, err)) {
                    return null;
                }
                break;
            } else {
                String temp = stringSet.substring(0, posComma);
                 if (getAndSaveColsNameAndValuesName(new StringBuilder(temp), err)) {
                    return null;
                }
                stringSet.delete(0, posComma + 1);
            }
        } while (true);
       
        // dieu kien de set
        if(posWhere != -1){
            this.condition = strBuff.substring(posWhere+5, strBuff.length());
        }
        return getSelectCommand();
 
    }

    private Command getSelectCommand() {
        this.selectSql.append("SELECT ");
        for(int i=0; i<colsName.size()-1; i++){
            this.selectSql.append(colsName.get(i)).append(", ");                
        }
        this.selectSql.append(colsName.get(colsName.size()-1));
        
        this.selectSql.append(" FROM ").append(this.tableName);
        if(this.condition != null)
            this.selectSql.append(" WHERE ").append(this.condition);
        return new Select(selectSql.toString(), manager);
    }

    private boolean getAndSaveColsNameAndValuesName(StringBuilder stringSet, MyError err) {
        int posEqual = stringSet.indexOf("=");
        if (posEqual == -1) {
            err.setError("Error!!! Khong co toan tu gan");
            return true;
        }
        String colName = stringSet.substring(0, posEqual);
        String value = stringSet.substring(posEqual +1,stringSet.length() -1);
        colsName.add(Command.ChuanHoa(colName));
        values.add(Command.ChuanHoa(value));
        return false;
    }

    @Override
    public ArrayList<Row> excute(MyError err) {
        Select select = (Select)this.getCommand(err);
        if(select == null)
            return null;
        ArrayList<Row> rows = select.excute(err);
        System.out.println(err.getError());
        /**
         * lay danh sach
         */
        for (int i = 0; i < rows.size(); i++) {
            Row r = rows.get(i);
            for (int j = 0; j < r.getListCell().size(); j++) {
                Cell cell = r.getListCell().get(j);
                for (int k = 0; k < this.colsName.size(); k++) {
                    if(cell.getName().equals(colsName.get(k))){
                        updateValue(cell,values.get(k));
                    }
                }
            }

        }
        return rows;
        
    }

    /**
     * @return the tableName
     */
    public String getTableName() {
        return tableName;
    }

    private void updateValue(Cell cell, String get) {
        
        int posOp = -1;
        char op= 'a';
        for(int i=0; i<strOperator.length; i++){
            if(get.indexOf(strOperator[i]) != -1){
                posOp = get.indexOf(strOperator[i]);
                op = strOperator[i].charAt(0);
            }
                
        }
        if(posOp == -1){ // khong co phep toan nao trong cau lenh
            cell.setData(get);
        }else{ // co phep toan trong cau lenh
            String strLeft = get.substring(0, posOp);
            String strRight = get.substring(posOp+1,get.length()-1);
            if(strLeft.equals(cell.getData())){// ten cot trung voi ten toan tu
                try{
                    int i = Integer.parseInt(strRight);
                    int value = Integer.parseInt(cell.getData());
                    switch(op){
                        case '+':
                            value +=  i;
                            break;
                        case  '-':
                            value -= i;
                        case '*':
                            value *= i;
                        case '/':
                            value /= i;                        
                    }
                    cell.setData(String.valueOf(value));
                }catch(Exception e){
                    return;
                }
                 
            }
        }
        
     
    }

   
   

}
